package com.kx.center.controller;

import java.security.GeneralSecurityException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kx.center.common.Cache;
import com.kx.center.entity.Account;
import com.kx.center.enumerate.MessageCode;
import com.kx.center.service.AccountService;
import com.kx.center.util.Response;

@Controller
@RequestMapping("/account")
public class AccountController {
	
	@Autowired
	AccountService service;

	@RequestMapping(value = "create", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String create(HttpServletRequest request) throws Exception {

		Account account = new Account();
		account.setDepartmentId(0);
		account.setEmail("eric.li0709@gmail.com");
		account.setLoginName("eric");
		account.setPassword("123456");
		account.setRoleId(1);
		account.setStatus(1);
		account.setSubscribe(false);
		account.setUserName("eric");
		service.createAccount(account);
		
		return null;
	}

	@RequestMapping(value = "login", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String login(HttpServletRequest request, HttpServletResponse response) throws Exception {
	

		String loginName = request.getParameter("username");
		String password = request.getParameter("password");
		
		Account account = null;
		
		try {
			account = service.findAccountByLoginNameAndPassword(loginName, password);
			
			if(account != null) {
				String token = account.getToken();
				
				Long validity = (long) Cache.get(Cache.TOKEN, token);
				
				response.setHeader("Access-Control-Expose-Headers", "X-Security-Token,X-Security-Token-Validity,X-Security-Username");
				response.setHeader("X-Security-Token", token);
				response.setHeader("X-Security-Token-Validity", validity.toString());
				response.setHeader("X-Security-Username", account.getUserName());
				return Response.success("验证通过");
			}
			
		} catch (GeneralSecurityException e) {
			return Response.error(MessageCode.UNKNOWN);
		}
		
		return Response.error(MessageCode.USERNAME_OR_PASSWORD_WRONG);
	}
}
